package com.sd.common.utils.cti;
import com.sd.cti.server.cmd.AgentLoginCmd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;

import java.lang.reflect.Field;
import java.text.ParseException;

/**
 * xml格式消息解析
 * @author yexinming
 *
 */
public class XmlMsgParser{

	private static final Logger log = LoggerFactory.getLogger(XmlMsgParser.class);

	/*public AgentLoginModel parser(String msgStr) {
		XmlHelper xmlHelper = XmlHelper.of(msgStr);
		return toMsgModel(xmlHelper);
	}*/
	/**
	 * xmlStr转换成对象
	 * @param xmlStr xml字符串
	 * @param clazz 转化成的灰
	 * @param <T> 返回范型
	 * @return
	 */
	public static <T> T parserToModel(String xmlStr,Class<T> clazz) throws Exception{
		T target = clazz.newInstance();

		XmlHelper xmlHelper = XmlHelper.of(xmlStr);
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			XPath xpathAnno = field.getAnnotation(XPath.class);
			if (xpathAnno == null) {
				continue;
			}
			
			String xpath    = xpathAnno.value();
			Class<?> type   = field.getType();
			String strValue = xmlHelper.getString(xpath);
			
			Object value = convert(type, strValue);
			if (!field.isAccessible()) {
				field.setAccessible(true);
			}
		    //设置属性
			field.set(target, value);
		}
		return target;
	}
	
	private static final Object convert(Class<?> type, String s) {
		try {
			return TypeConverter.me().convert(type, s);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] args) throws Exception{
			String xml =
					"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" +
							"<bookstore>\n" +
							"<book>\n" +
							"<title lang=\"eng\">Harry Potter</title>\n" +
							"<price>29.99</price>\n" +
							"</book>\n" +
							"<book>\n" +
							"<title lang=\"eng\">Learning XML</title>\n" +
							"<price>39.95</price>\n" +
							"</book>\n" +
							"</bookstore>";

		String xmlAgentlogin = "<?xml version='1.0' encoding=\"UTF-8\"?>"+
				"<root>"+
				"<agentId>zj1431</agentId>"+
				"<station>018867962556</station>"+
				"<passWord>123456</passWord>"+
				"<userData>123</userData>"+
				"<permission>picc123</permission>"+
				"<state>3</state>"+
				"<reason>hahaha</reason>"+
				"<ip>10.133.240.239|157.122.153.67</ip>"+
				"<port>9000|9000</port>"+
				"<event>Login</event >"+
				"</root>";

			XmlHelper xmlHelper = XmlHelper.of(xml);
			String title1 = xmlHelper.getString("//book[1]/title");
			System.out.println(title1);

			String titleLang = xmlHelper.getString("//book[1]/title/@lang");
			System.out.println(titleLang);

			Number price1 = xmlHelper.getNumber("//book[1]/price");
			System.out.println(price1.doubleValue());

			Node node = xmlHelper.getNode("//book[2]/title");
			String titleLang2 = xmlHelper.getString(node, "@lang");
			System.out.println(titleLang2);

		    AgentLoginCmd agentLoginModel = parserToModel(xmlAgentlogin, AgentLoginCmd.class);
            System.out.println("agentLoginModel"+agentLoginModel);
	}
}
